<template>
    <div>
        <global-tables
            :total="total"
            :list="list"
            :loading="loading"
            :columns="columns"
            :current="search.pageindex"
            @changePage="handleChangePage"
            @handleAllSelect="handleAllSelect"
        >
            <Form :model="search" :label-width="80">
                <div class="table-top-wrap">
                    <div>
                        <Button v-if="isAddBtn" class="features-btn" @click="handleBtnClick(null,'add')">
                            <Icon type="md-add" size="18"/>新建
                        </Button>
                    </div>
                    <div class="table-top-wrap-bottom">
                        <div>
                            <Select v-model="search.groupid" style="width:100px;margin:0 10px" placeholder="审批类别">
                                <Option :value="item.ID + ''" v-for="item in dataList" v-bind:key="item.id">{{item.GroupName}}</Option>
                            </Select>
                        </div>
                        <div>
                            <input type="text" class="style-input" @keyup.enter="handleSearch" v-model="search.keyword" placeholder="请输入发起人 / 审批人">
                            <i-input style="display:none"></i-input>
                        </div>
                        <div>
                            <Button icon="ios-search" class="search-btn" @click="handleSearch">搜索</Button>
                        </div>
                    </div>
                </div>
            </Form>
        </global-tables>
        <div>
            <!-- 新建 -->
            <Modal :mask-closable="false" v-model="isModal" :title="ApprovalTitle">
                <div v-if="isModal">
                    <Form ref="formItem" :model="formItem" :rules="ruleValidate" :label-width="100">
                        <Row>
                            <i-col :lg="{ span: 15}">
                                <FormItem label="审批类别" prop="GroupID">
                                    <AsyncSelect
                                        :currentModel="formItem.GroupID"
                                        :url="'ComFlowGroup/GetListJson'"
                                        :value="'GroupID'"
                                        :parameter="{comid}"
                                        :typeOf="'ApprovalCategory'"
                                        @setDictionaries="setDictionaries"
                                    ></AsyncSelect>
                                </FormItem>
                            </i-col>
                        </Row>
                        <Row>
                            <i-col :lg="{ span: 18}">
                                <FormItem label="发起人" prop="sponsor">
                                    <Row>
                                        <i-col span="20">
                                            <Input :disabled="true" type="text" v-model="formItem.sponsor" placeholder="请选择发起人"/>
                                        </i-col>
                                        <i-col span="3" offset="1">
                                            <Button @click="handlePersonnel('sponsor')">选择</Button>
                                        </i-col>
                                    </Row>
                                </FormItem>
                            </i-col>
                            <i-col :lg="{ span: 18}">
                                <FormItem label="审批人" prop="approver">
                                    <Row>
                                        <i-col span="20">
                                            <Input :disabled="true" type="text" v-model="formItem.approver" placeholder="请选择审批人"/>
                                        </i-col>
                                        <i-col span="3" offset="1">
                                            <Button @click="handlePersonnel('approver')" :disabled="isApprover">选择</Button>
                                        </i-col>
                                    </Row>
                                </FormItem>
                            </i-col>
                            <i-col :lg="{ span: 24}">
                                <FormItem label="流程">
                                    <Steps :current="currentSteps" direction="vertical">
                                        <Step title="发起人" :content="formItem.sponsor"></Step>
                                        <Step title="审批人" v-for="(item , index) in approverList" :key="index" :content="item.content"></Step>
                                    </Steps>
                                </FormItem>
                            </i-col>
                        </Row>
                    </Form>
                </div>
                <div slot="footer">
                    <Button size="large" @click="handleClose('listClose')">取消</Button>
                    <Button type="primary" size="large" @click="handleSubmit('formItem')">确定</Button>
                </div>
            </Modal>
            <!-- 人员选择 -->
            <Modal :mask-closable="false" v-model="isPersonnelModal" :title="ModalTitle">
                <div v-if="isModal">
                    <Form ref="formItem" :model="formItem" :rules="ruleValidate" :label-width="100">
                        <Row>
                            <i-col :lg="{ span: 15}">
                                <FormItem label="部门">
                                    <Select>
                                        <Option
                                            @click.native="changeDepartment(item.ID)"
                                            v-for="item in roleList.CList"
                                            :value="item.ID + ''"
                                            :key="item.ID"
                                        >{{item.DepName}}</Option>
                                    </Select>
                                </FormItem>
                            </i-col>
                            <i-col :lg="{ span: 24}" v-if="personnelList.length > 1">
                                <FormItem label="人员">
                                    <CheckboxGroup v-model="currentPersonnel" @on-change="handleChangeCheckBox">
                                        <Checkbox v-for="item in personnelList" :key="item.ID" :label="item.ID + `/${item.RealName}`">{{item.RealName}}</Checkbox>
                                    </CheckboxGroup>
                                </FormItem>
                            </i-col>
                        </Row>
                    </Form>
                </div>
                <div slot="footer">
                    <Button size="large" @click="handleClose('userClose')">取消</Button>
                    <Button type="primary" size="large" @click="setPersonnel('formItem')">确定</Button>
                </div>
            </Modal>
        </div>
    </div>
</template>

<script>
/**
 * 审批设置
 */
import { cyclicRouting } from '@/util';
import { getModulePermission } from '@/api/user';
import GlobalTables from '@/components/GlobalTables';
import AsyncSelect from '@/components/AsyncSelect';
import Api from './service';
//import { setTimeout } from 'timers';
export default {
    name: 'SystemFlowset',
    components: {
        GlobalTables,
        AsyncSelect
    },
    data() {
        return {
            isModal: false,
            loading: true,
            isApprover: false,
            total: 0,
            ModalTitle: '人员选择',
            ApprovalTitle: '新建审批设置',
            isAddBtn: false,
            isEdit: false,
            currentSteps: -1,
            approverList: [],
            personType: null,
            listType: null,
            isPersonnelModal: false,
            allSelectArr: null,
            comid: JSON.parse(sessionStorage.getItem('user')).comid,
            roleList: [],
            personnelList: [],
            currentPersonnel: [],
            dataList: [],
            itemId: null,
            formItem: this.initFormValidate(),
            ruleValidate: this.initRuleValidate(),
            search: {
                keyword: '',
                pageindex: 1,
                groupid: '',
                pagesize: 10,
                type: ''
            },
            columns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '审批类别',
                    key: 'GroupName'
                },
                {
                    title: '发起人',
                    key: 'ProPoserName'
                },
                {
                    title: '审批流',
                    key: 'ApprovedUserName'
                },
                {
                    title: '操作人',
                    key: 'LastModifyName'
                },
                {
                    title: '时间',
                    key: 'LastModifyTime'
                },
                {
                    title: '操作',
                    width: 200,
                    align: 'center',
                    render: (h, params) => {
                        const { isEdit } = this;
                        return h('div', [
                            isEdit &&
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            background: '#5ab1ef',
                                            border: 'none',
                                            marginRight: '5px'
                                        },
                                        on: {
                                            click: () => {
                                                this.handleBtnClick(params.row, 'edit');
                                            }
                                        }
                                    },
                                    '修改'
                                )
                        ]);
                    }
                }
            ],
            list: []
        };
    },
    mounted() {
        /* 获取菜单的id */
        cyclicRouting(JSON.parse(sessionStorage.getItem('user')).menuList, this.$route, id => {
            /* 按钮权限请求 */
            getModulePermission({
                roleid: JSON.parse(sessionStorage.getItem('user')).roleid,
                moduleid: id
            }).then(res => {
                /* 按钮权限赋值 */
                for (let item in res.data) {
                    if (res.data[item].name == 'add') {
                        /* 如果用户权限有新建 */
                        this.isAddBtn = true;
                    } else if (res.data[item].name == 'edit') {
                        this.isEdit = true;
                    }
                }
                /* 列表请求 */
                this.getTablesListData();
                this.getItemValueData();
            });
        });
    },
    methods: {
        /* 表格数据请求 */
        getTablesListData() {
            const data = this.search;
            Api.getTablesList(data).then(res => {
                this.list = res.rows;
                this.loading = false;
                this.total = res.records;
            });
        },
        /* 模糊搜索类别选择*/
        getItemValueData() {
            Api.getItemValue({
                comid: this.comid
            }).then(res => {
                this.dataList = res.data;
            });
        },
        /* 表格分页方法 */
        handleChangePage(type, page) {
            this.loading = true;
            if (type == 'page') {
                this.search.pageindex = page;
                this.getTablesListData();
            } else {
                this.search.pagesize = page;
                this.getTablesListData();
            }
        },
        /* 人员选择按钮点击 */
        handlePersonnel(type) {
            this.currentPersonnel = [];
            Api.getRoleList().then(res => {
                this.roleList = res.data;
            });
            this.isPersonnelModal = true;
            this.personType = type;
            if (this.personType == 'sponsor') {
                this.formItem.ProposerID = [];
            } else {
                this.currentPersonnel = [];
            }
        },
        /* 人员选择点击*/
        handleChangeCheckBox() {
            if (this.personType == 'sponsor') {
                this.formItem.ProposerID = [];
                this.formItem.ProposerName = [];
            } else {
                this.formItem.ApprovedUserID = [];
                this.formItem.ApprovedUserName = [];
            }
            for (let item in this.currentPersonnel) {
                if (this.personType == 'sponsor') {
                    this.formItem.ProposerID.push(
                        this.currentPersonnel[item].substring(0, this.currentPersonnel[item].indexOf('/'))
                    );
                    this.formItem.ProposerName.push(
                        this.currentPersonnel[item].substring(
                            this.currentPersonnel[item].indexOf('/') + 1,
                            this.currentPersonnel[item].length
                        )
                    );
                } else {
                    this.formItem.ApprovedUserID.push(
                        this.currentPersonnel[item].substring(0, this.currentPersonnel[item].indexOf('/'))
                    );
                    this.formItem.ApprovedUserName.push(
                        this.currentPersonnel[item].substring(
                            this.currentPersonnel[item].indexOf('/') + 1,
                            this.currentPersonnel[item].length
                        )
                    );
                }
            }
        },
        /* 人员确定 */
        setPersonnel() {
            this.isPersonnelModal = false;
            if (this.personType == 'sponsor') {
                this.formItem.sponsor = this.formItem.ProposerName.join(' / ');
                this.isApprover = false;
                if (this.formItem.sponsor == '') {
                    // this.isApprover = true;
                    // this.approverList = [];
                    // this.currentSteps = -1;
                    this.formItem.ProposerID.push('0');
                    this.formItem.ProposerName.push('所有人');
                    //console.log(this.formItem);
                    this.formItem.sponsor = '所有人';
                }
            } else {
                if (this.formItem.sponsor == '') {
                    // this.isApprover = true;
                    // this.approverList = [];
                    // this.currentSteps = -1;
                    this.formItem.ProposerID.push('0');
                    this.formItem.ProposerName.push('所有人');
                    //console.log(this.formItem);
                    this.formItem.sponsor = '所有人';
                }
                this.formItem.approver = this.formItem.ApprovedUserName.join(' / ');
                if (this.formItem.approver == '') {
                    return false;
                } else {
                    this.approverList.push({
                        content: this.formItem.approver
                    });
                }
            }
            this.currentSteps += 1;
        },
        /* 表格查询 */
        handleSearch() {
            this.loading = true;
            this.getTablesListData();
        },
        /* 关闭对话框 */
        handleClose(type) {
            this.listType = type;
            if (this.listType == 'userClose') {
                this.isPersonnelModal = false;
            } else {
                this.isModal = false;
            }
        },
        /* 复选框选中 */
        handleAllSelect(list) {
            let arr = [];
            for (let item in list) {
                arr.push(list[item].ID);
                arr.join(',');
            }
            arr = arr.join(',');
            this.allSelectArr = arr;
        },
        /* 部门点击 */
        changeDepartment(id) {
            this.personnelList = this.roleList.UList.filter(item => {
                return id == item.RoleID;
            });
        },
        /* 对话框提交 */
        handleSubmit() {
            const { formItem, itemId } = this;
            // this.$refs[name].validate(valid => {
            //     if (valid) {
            //console.log(formItem.ProposerName);
            let data = {
                ID: itemId,
                ComID: this.comid,
                GroupID: formItem.GroupID,
                ProposerID: formItem.ProposerID.join('/'),
                ProPoserName: formItem.ProposerName.join('/'),
                ApprovedUserID: formItem.ApprovedUserID.join('/'),
                ApprovedUserName: formItem.ApprovedUserName.join('/'),
                Remark: ''
            };
            if (formItem.GroupID == '') {
                this.$Message.error('请选择审批类别');
            } else if (formItem.approver == '') {
                this.$Message.error('请选择审批人');
            } else {
                Api.postSubmitForm(data).then(res => {
                    if (res.state == 'success') {
                        this.$Message.success('操作成功');
                        this.loading = true;
                        this.handleClose();
                        this.getTablesListData();
                    } else {
                        this.$Message.error(res.message);
                    }
                });
            }

            //     }
            // });
        },
        /* 对话框操作点击 */
        handleBtnClick(item, type) {
            this.initFormValidate();
            this.isModal = true;
            //this.isApprover = true;
            this.initFormValidate();
            this.itemId = 0;
            this.isModal = true;
            if (type == 'edit') {
                this.type = 'edit';
                this.itemId = item.ID;
                this.ApprovalTitle = '修改用户';
                this.isApprover = false;
                this.approverList = [];
                this.personnelList = [];
                // 获取一条的id;
                Api.getItemInfo({
                    keyvalue: item.ID
                }).then(res => {
                    // 赋值给表单;
                    const newApprovedUserName = res.data.ApprovedUserName.split(',');
                    for (let item in newApprovedUserName) {
                        this.approverList.push({
                            title: '审批人',
                            content: newApprovedUserName[item]
                        });
                    }
                    this.currentSteps = newApprovedUserName.length;
                    // }
                    this.formItem = {
                        ...this.formItem,
                        //ID: res.data.GroupName,
                        sponsor: res.data.ProPoserName,
                        GroupID: res.data.GroupID + '',
                        approver: res.data.ApprovedUserName
                        // LastModifyName: res.data.LastModifyName,
                        // LastModifyTime: res.data.LastModifyTime
                    };
                });
            } else {
                this.approverList = [];
                this.currentSteps = -1;
                this.ApprovalTitle = '新建用户';
                this.isTime = true;
                this.formItem = this.initFormValidate();
            }
        },
        /* 审批类别选择 */
        setDictionaries(item, value) {
            this.formItem[value] = item.ID + ' ';
        },
        /* 表单数据 */
        initFormValidate() {
            return {
                sponsor: '',
                approver: '',
                ID: '',
                ComID: '',
                GroupID: '',
                ProposerID: [],
                ProposerName: [],
                ApprovedUserID: [],
                ApprovedUserName: [],
                Remark: ''
            };
        },
        /* 表单校验 */
        initRuleValidate() {
            return {
                sponsor: [{ required: true, message: '请选择发起人', trigger: 'blur' }],
                approver: [{ required: true, message: '请选择审批人', trigger: 'click' }],
                GroupID: [{ required: true, message: '请输入审批类别', trigger: 'click' }]
            };
        }
    }
};
</script>

<style lang="less" scoped>
.form-item-width {
    width: 300px;
}
.btn-wrap {
    margin: 0 15px;
}
.dle-btn {
    margin: 0 10px;
}
.search-con {
    padding: 10px 0;
    .search {
        &-col {
            display: inline-block;
            width: 200px;
        }
        &-input {
            display: inline-block;
            width: 200px;
            margin-left: 2px;
        }
        &-btn {
            margin-left: 2px;
        }
    }
}
</style>


